package mammuthus.web.service;

import mammuthus.web.bean.ProjectConfBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by fbj on 15-2-5 下午1:49.
 */
@Service
public class ProjectConfService {

	private JdbcTemplate jdbcTemplate;

	@Autowired
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public List<ProjectConfBean> getVersions(String path, int page, int pageSize){

		if(page <= 0) page = 1;
		return jdbcTemplate.query("select * from t_project_conf where path = ? order by id desc limit ? offset ?",
				new BeanPropertyRowMapper(ProjectConfBean.class),
				path, pageSize, (page - 1) * pageSize

		);
	}

	public boolean isExist(String path, String version){
		int count = jdbcTemplate.queryForInt("select count(1) from t_project_conf where path = ? and version = ?", path, version);

		return count > 0;
	}
	public void addVersion(String path, String version, String comment, String conf){

			jdbcTemplate.update("insert into t_project_conf(path, version, comment, conf,insert_time) values(?,?,?,?,?)",
					path, version, comment, conf, new Date()
			);

	}

	public ProjectConfBean getProjectConfById(int id){

		List<ProjectConfBean> list =  jdbcTemplate.query("select * from t_project_conf where id = ?", new BeanPropertyRowMapper(ProjectConfBean.class), id);
		if(list != null && list.size() > 0){
			return list.get(0);
		}else{
			return null;
		}
	}

	public ProjectConfBean getLastedProjectConfByPath(String path){

		List<ProjectConfBean> list =  jdbcTemplate.query("select * from t_project_conf where path = ? order by id desc limit 1", new BeanPropertyRowMapper(ProjectConfBean.class), path);

		if(list != null && list.size() > 0){
			return list.get(0);
		}else{
			return null;
		}
	}


}


